<template>
  <div class="box-container">
    <div v-if="defaultViewPage == 'default'">
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col
          :lg="6"
          :md="12"
          :sm="24"
          :xl="6"
          :xs="24"
          v-for="item in workOrderCount"
          :key="item.status"
          @click="handleCount(item)">
          <BiDescriptionsCard
            height="132px"
            cursor="pointer"
            :background="workOrderCountStatus == item.status ? '#0052d9' : '#498adb'"
            :title="item.status_str"
            :countConfig="{
              startValue: 0,
              endValue: item.count,
              decimals: 0,
              prefix: '',
              suffix: '',
              separator: ',',
              duration: 8000,
            }" />
        </el-col>
        <!-- <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <BiDescriptionsCard background="#0052d9" percentage="5单" title="进行中任务单">
            <template #chart> </template>
          </BiDescriptionsCard>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <BiDescriptionsCard background="#0052d9" percentage="5单" title="生产已完成任务单">
            <template #chart> </template>
          </BiDescriptionsCard>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
          <BiDescriptionsCard background="#0052d9" percentage="5单" title="发货已完成任务单">
            <template #chart> </template>
          </BiDescriptionsCard>
        </el-col> -->
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" class="data-tabs">
          <!-- <span
            v-for="(item, i) in visualList"
            :key="i"
            @click="handleVisual(item)"
            :class="activeVisual == item.id ? 'active' : ''">
            {{ item.title }}

            <div @click.stop class="close">
              <el-popconfirm width="220" icon-color="#626AEF" title="确定删除此视角吗?">
                <template #reference>
                  <BiIcons class="icon" name="CloseBold" />
                </template>
                <template #actions="{ cancel }">
                  <el-button size="small" @click="cancel">取消</el-button>
                  <el-button type="primary" size="small" @click.stop="handleDetele(item.id)"> 确认 </el-button>
                </template>
              </el-popconfirm>
            </div>
          </span> -->

          <el-tabs style="width: 100%;" v-model="activeVisual" type="card" editable class="demo-tabs" @edit="handleDetele" @tab-change="handleVisual">
            <el-tab-pane v-for="(item, i) in visualList" :key="i" :label="item.title" :name="item.id"> </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="12" class="data-tabs">
          <div class="flex_end">
            <ElButton type="primary" @click="defaultViewPage = 'task'">任务单详情</ElButton>
            <ElButton type="primary" @click="defaultViewPage = 'source'">产品溯源</ElButton>
            <ElButton type="primary" @click="handleAddVisual()">新增视角</ElButton>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-loading="loading">
        <BiGatt ref="ganttChar" optType="edit" :ids="[]" />
      </el-row>
      <el-dialog v-model="dialogVisible" :close-on-click-modal="false" title="新增视角" width="500">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon>
          <el-form-item label="视角名称" prop="title">
            <el-input v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="选择相关工序" prop="processIds">
            <el-select v-model="ruleForm.processIds" multiple placeholder="">
              <el-option v-for="item in workList" :key="item?.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfimVisual(ruleFormRef)"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div v-if="defaultViewPage == 'source'">
      <ProduceDetail ref="produceDetailRef" />
    </div>
    <div v-if="defaultViewPage == 'task'">
      <TaskDetail ref="taskDetailRef" :visualId="activeVisual || 1" :status="workOrderCountStatus" />
    </div>
  </div>
</template>
<!-- 生产看板 -->
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElButton, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { addVisual, deleteVisual, getTaskByLoginUser, getTaskVisualDetail, getWorkOrderCount } from '../api/taskBi';
import ProduceDetail from './components/ProduceDetail.vue';
import TaskDetail from './components/TaskDetail.vue';
import { listAll } from '../api/all';

defineOptions({
  name: 'Produce',
});

defineProps({
  type: {
    type: Number,
    default: 2, //统计类型:1-代表本周;2-代表本月;3-代表本年;4-代表自定义时间
  },
  timeRange: {
    type: Object,
    default: {
      startTime: '',
      endTime: '',
    }, //时间区间
  },
});

const defaultViewPage = ref('default'); // 显示页面
const loading = ref(false); //
const visualList = ref<any>([]); //视角列表
const tasksData = ref({}); //gant数据
const ganttChar = ref<any>(null); //gant实例
const activeVisual = ref(1); //当前视角
const dialogVisible = ref(false); //弹窗
const workList = ref<any>([]); //工序数据
const workOrderCount = ref<any>([]); //订单统计数量
const workOrderCountStatus = ref<string>('all'); //订单统计数量下标

// 实例
const produceDetailRef = ref();
const taskDetailRef = ref();

// 表单
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<any>({
  title: null,
  processIds: null,
});
const rules = {
  title: [{ required: true, message: '视角名称不能为空！', trigger: 'blur' }],
  processIds: [{ required: true, message: '请选择选择相关工序！', trigger: 'blur' }],
};

// 获取页面数据
const getPageData = (isNavSwitch = false) => {
  // 切换看板模块
  if (isNavSwitch) defaultViewPage.value = 'default';
  // 一键溯源模块
  if (defaultViewPage.value == 'source') return produceDetailRef.value.getPageData();
  // 任务单详情模块
  if (defaultViewPage.value == 'task') return taskDetailRef.value.getPageData();

  getGantData();
  getCisualList();
  getWorkOrderCountData();
};

const getWorkOrderCountData = async () => {
  try {
    const res = await getWorkOrderCount({});

    workOrderCount.value = res.data.map((item: any) => {
      return {
        ...item,
        status_str: returnStatusStr(item.status),
      };
    });
  } catch (error) {}
};

// 获取gant数据
const getGantData = async () => {
  loading.value = true;

  try {
    getCisualList();

    let res = await getTaskVisualDetail({ visualId: activeVisual.value || 1, status: workOrderCountStatus.value });
    const { returnData, returnLinkData } = res.data;

    ganttChar.value.initData({
      data: returnData,
      links: returnLinkData,
    });

    tasksData.value = {
      data: returnData,
      links: returnLinkData,
    };

    loading.value = false;
  } catch (error) {}
};
// 获取视角tabs
const getCisualList = async () => {
  let resUser = await getTaskByLoginUser();
  visualList.value = resUser.data;
};
// 选择视角
const handleVisual = (id: any) => {
  activeVisual.value = id;
  getGantData();
};
// 添加视角
const handleAddVisual = () => {
  listAll().then((_res) => {
    workList.value = _res.data.map((_item: any) => {
      return {
        value: _item.processId,
        label: _item.processName,
      };
    });

    dialogVisible.value = true;
  });
};
// 确认新增视角
const handleConfimVisual = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addVisual({
        ...ruleForm,
      }).then((_res) => {
        ElMessage.success('添加成功!');
        dialogVisible.value = false;
        getPageData();
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 删除视角
const handleDetele = (id: string | number) => {
  ElMessageBox.alert('是否确认删除此视角？', '提示', {
    confirmButtonText: '确认',
    callback: (actions: any) => {
      if (actions == 'confirm') {
        deleteVisual(id).then((_res) => {
          ElMessage.success('删除成功!');
          getCisualList();
        });
      }
    },
  });
};
// 筛选统计
const handleCount = ({ status }: any) => {
  workOrderCountStatus.value = status;
  getGantData();
};

// 状态标题
const returnStatusStr = (v: string) => {
  let str = '';
  switch (v) {
    case 'all':
      str = '全部任务单';
      break;
    case 'finish':
      str = '已完成任务单';
      break;
    case 'other':
      str = '未完成任务单';
      break;
    case 'zero':
      str = '备产任务单';
      break;
    default:
      break;
  }
  return str;
};

defineExpose({
  getPageData,
});
</script>

<style lang="scss" scoped>
.box-container {
  padding-bottom: 0px;

  .demo-tabs > .el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }

  .data-tabs {
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    :deep() {
      .el-tabs--top{
        margin-bottom: -10px;
      }
      .el-tabs__new-tab {
        display: none;
      }
    }

    span {
      font-family: 'PingFangSC-Regular', 'PingFang SC';
      font-weight: 400;
      font-style: normal;
      font-size: 16px;
      color: #666666;
      cursor: pointer;
      position: relative;

      background-color: #fff;
      padding: 14px 30px;
      font-size: 14px;
      border-left: 1px solid #0052d9;

      &.active {
        color: #0052d9;
      }

      .close {
        position: absolute;
        top: 0;
        right: 0px;
        z-index: 1000;

        display: block;
        width: 15px;
        height: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        pointer-events: auto;

        .icon {
          pointer-events: auto;
        }
      }
    }
  }
}
</style>
